# -*- coding: utf-8 -*-

import os
import sys
import datetime
import pytz
import jinja2
from openerp.exceptions import ValidationError
from openerp.osv import osv

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package
    # loader.
    path = os.path.realpath(os.path.join(
        os.path.dirname(__file__), '..', 'views'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_lodop', "report")

env = jinja2.Environment(loader=loader, autoescape=True)


def strftime(str, fmt):
    dt = datetime.datetime.strptime(str, '%Y-%m-%d %H:%M:%S')
    dt = dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
    return dt.strftime(fmt.encode('utf-8')).decode('utf-8')

env.filters['strftime'] = strftime


class report_fake_outbound_order_lodop(osv.AbstractModel):

    """Model used to embed lodop reports"""
    _name = 'report.outbound_order_lodop'
    _template = None
    _wrapped_report_class = None

    #假单打印成出库单
    def render_html(self, cr, uid, ids, data=None, context=None):
        model_name = 'sale.order'
        report_obj = self.pool[model_name]
        order = report_obj.browse(cr, uid, ids[0], context=context)
        template = env.get_template("outbound_order_lodop.html")
        options = data or {}

        #注释掉，不把真单换成假单了，仓库理货需要真单来理货
        # fake_order_ids = report_obj.search(cr, uid, [('real_so_id', '=', ids[0])], context=context)
        # if fake_order_ids:
        #     fake_order_id = fake_order_ids[0]
        #     order = report_obj.browse(cr, uid, fake_order_id, context=context)

        # if order.real_so_id:
        #     fake_order = self.pool.get('sale.order').browse(
        #         cr, uid, order.real_so_id.id, context=context)
        # else:
        #     fake_order = self.pool.get('sale.order').browse(
        #         cr, uid, fake_sale_obj.real_so_id.id, context=context)
        category_ids = order.partner_id.category_id
        is_vip = False
        for category_id in category_ids:
            if category_id.name == u'大客户':
                is_vip = True

        # 取得纸质发票个数
        official_invoice_map = {} #{False: 1L, True: 1L}
        if order.sale_order_invoice:
            cr.execute("SELECT is_outer_invoice, COUNT(*) as invoice_count FROM official_invoice_lines WHERE official_invoice_id=%s GROUP BY is_outer_invoice", (order.sale_order_invoice.id, ))
            official_invoiced_line = cr.dictfetchall()
            for invoiced_line in official_invoiced_line:
                official_invoice_map[invoiced_line.get('is_outer_invoice')] = invoiced_line.get('invoice_count')
        #当前用户
        curUser = self.pool.get('res.users').browse(
            cr, uid, uid, context=None)
        #只打印一张的时候，也就是非批量打印的时候才设置已打印状态
        if len(ids) == 1:
            order.write({'is_tallying_printed': True})
        chinese = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆',
                   '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}

        #查找是否有对应的假单
        fake_order_id = report_obj.search(cr, uid, [('real_so_id', '=', order.id)], context=context)
        have_fake_order = False
        if fake_order_id:
            have_fake_order = True
        #是否假单
        is_fake_order = False
        if order.real_so_id:
            is_fake_order = True
        return template.render({
            'order': order,
            'ids': ids,
            'curUser': curUser,
            'debug': context,
            'chinese': chinese,
            'warning': False,
            'have_fake_order': have_fake_order,
            'is_fake_order': is_fake_order,
            'options': options,
            'official_invoice_map': official_invoice_map,
            'is_vip': is_vip
        })
